/*
 *                    BioJava development code
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  If you do not have a copy,
 * see:
 *
 *      http://www.gnu.org/copyleft/lesser.html
 *
 * Copyright for this code is held jointly by the individual
 * authors.  These should be listed in @author doc comments.
 *
 * For more information on the BioJava project and its aims,
 * or to join the biojava-l mailing list, visit the home page
 * at:
 *
 *      http://www.biojava.org/
 *
 * Created on 15.04.2004
 * @author Andreas Prlic
 *
 */
package dasregistry ;

import java.io.Serializable;
import java.sql.*                             ;
import java.util.ArrayList;

import javax.sql.DataSource                   ;

import org.biojava.dasobert.das.DasSpec;
import org.biojava.dasobert.dasregistry.*;
import org.biojava.services.das.registry.DasRegistry;
import org.biojava.services.das.registry.DasRegistrySql;
import org.biojava.services.das.registry.DasSourceTester;

import javax.naming.Context;
import javax.naming.InitialContext;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import dasregistry.validation.Validator;


public class updateBean 
implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 7470528362162041019L;

	private final static String DATASOURCE_NAME = "jdbc/mysql";

	public static int DATABASE_ERROR = 4;

	/** the character that separates the prefix from the number */
	public static String PREFIXSPLIT = "_" ;

	public static int PASSKEY_OK    =  1;
	public static int PASSKEY_WRONG = -1;

	//protected DataSource dataSource ;  

	String dasurl      ;
	String nickname;
	String adminemail  ;
	String description ;
	String[] cs_types;
	String [] capabilities ;
	String[] labels;
	String[] testCodes;
	String helperurl;
	String organism;
	String cs_name;
	String alertAdmin;
	String spec="";


	//ApplicationContext context;

	public String getSpec() {
		return spec;
	}


	public void setSpec(String spec) {
		this.spec = spec;
	}


	public updateBean() {
		System.out.println("updateBean init");

		cs_types         = new String[0];
		capabilities     = new String[0];
		labels           = new String[0];
		testCodes        = new String[0];
		helperurl        = "";
		cs_name          = "";
		nickname         = "";
		spec="";

		
	}


	private DataSource getDataSource() {
		DataSource dataSource = null;
		try {
			Context env = (Context) new InitialContext().lookup("java:comp/env");
			dataSource = (DataSource) env.lookup(DATASOURCE_NAME);
		} catch ( Exception e) {
			e.printStackTrace();
		}   
		return dataSource;
	}
	
	/** ds_id .. Unique ID from DasSource
	returns :
	 * 1 - update o.k.
	 * 3 - server failed validataion test
	 * 4 - database error -  could not add server to database
	 * 5 - unknown capability
	 * 6 - adminemail not a valid email address
	 * 7 - dasurl not valid
	 * 8 - description not valid
	 * 9 - coordSystem not valid
	 * 10 - capabilities not valid
	 * 11 - testCode not found.
	 * 12 - nickname already in use / invalid nickname
	 * 13 - unknown error occured...
	 * 14 - source was not really valid but will allow changes
	 * @param ds_id 
	 * @return flag of the status
	 */

	public int updateMe(String ds_id) {
		System.out.println("UPDATING " + ds_id + " " + dasurl+" " + nickname +" " + adminemail);
		// validate server first ...
		int status = 13 ;		
		BeanFactory ctx=(new ClassPathXmlApplicationContext("SpringDAO.xml"));
		DasRegistrySql dsl=(DasRegistrySql)ctx.getBean("registryBean");
		
		
		 DasSourceTester tester = new DasSourceTester(dsl);

		 String ontology = "false";
		//DasRegistrySql drsql = new DasRegistrySql();
		 ArrayList listCaps=new ArrayList();
	for(String listCap:capabilities){
		listCaps.add(listCap);
	}
		status = tester.testArguments(dasurl,
				nickname,
				adminemail,
				description,
				cs_types,
				listCaps,
				labels,
				helperurl,
				testCodes,false, ontology);

		if ( status  != DasSourceTester.STATUS_OK){
			return status;
		}

		DasSource ds = new Das1Source();
		ds.setUrl(dasurl);
		ds.setNickname(nickname);
		ds.setAdminemail(adminemail);
		ds.setDescription(description);

		Connection conn =null;
		
		try {
						
			
			DataSource dataSource = getDataSource();
			conn = dataSource.getConnection();
			DasCoordinateSystem[] dcsarr  = dsl.getCoordSysByString(conn,cs_types, testCodes);	    
			ds.setCoordinateSystem(dcsarr);
			ds.setCapabilities(capabilities);
			ds.setLabels(labels);
			ds.setHelperurl(helperurl);
			ds.setSpecification(spec);
			//ds.setTestCode(testCode);
			if ( (alertAdmin != null) &&( alertAdmin.equals("1") ))
				ds.setAlertAdmin(true);
			else
				ds.setAlertAdmin(false);

			ds.setId(ds_id);boolean vOntology=false;
			if(ontology.equals("true")){
				vOntology=true;
			}
			Validator validator=new Validator();
			System.out.println("spec="+spec);
			DasValidationResult result=validator.validate(DasSpec.convertToRegistrySpecification(spec), dasurl, listCaps, dcsarr, vOntology, true, dsl,ds_id);
			if(!result.isOverallValid()){
				//return 3; lets not disallow updates as hopefully people will be improving the source????
			}
			status = dsl.updateSource(ds);

		} catch (SQLException e ) {
			e.printStackTrace();
			status = DATABASE_ERROR;
		} finally {
			if ( conn != null ) {
				try { 		   
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}

		}
		return status ;
	}

	public void setAlertAdmin(String flag) {
		alertAdmin = flag;
	}

	public String getAlertAdmin() {
		return alertAdmin;
	}

	public void setCSTypes(String[] s) {
		cs_types = s ;	
	}

	public String[] getCSTypes(){
		//for ( int i = 0 ; i<coordinateSystem.length; i++){
		//System.out.println(" coordsys " + i + " " + coordinateSystem[i]);
		//}
		//System.out.println("returning coordinateSystem "+ coordinateSystem);
		return cs_types ;
	}

	/*public String getCSTypes(int position){
      return cs_types[position] ;
      }*/


	public void setCapabilities (String[] s) {
		capabilities = s ;	
	}

	public String[] getCapabilities () {
		//for ( int i = 0 ; i<capabilities.length; i++){
		//System.out.println(" cap " + i + " " + capabilities[i]);
		//}
		//System.out.println("getCapabilities" + capabilities);
		return capabilities ;
	}

	public void setDasurl( String u )
	{
		char lastChar = u.charAt(u.length()-1);
		if ( lastChar  != '/')
			u += "/";

		dasurl = u;
	}

	public void setAdminemail( String value )
	{
		adminemail = value;
	}

	public void setDescription( String value )
	{
		description = value;
	}

	public String getDasurl() { 
		return dasurl; 
	}

	public void setNickname(String name){
		nickname = name;
	}
	public String getNickname(){
		return nickname;
	}

	public String getAdminemail() { return adminemail; }

	public String getDescription() { return description; }

	public void setLabels(String[] l) {
		labels = l ;
	}

	public String[] getLabels() {
		return labels;
	}

	public void setTestCodes(String[] codes) {
		testCodes = codes;
	}

	public String[] getTestCodes() {
		return testCodes;
	}

	public void setHelperurl(String url) {
		helperurl = url;
	}

	public String getHelperurl() {
		return helperurl;
	}



	/** validate the Passkey for a das source 
	returns:
	PASSKEY_OK: key is o.k.
	PASSKEY_FAILED: key is bad...
	 * @param ds_id 
	 * @param passkey 
	 * @return PASSKEY_OK or PASSKEY_FAILED
	 */

	public int validatePasskey(String ds_id , String passkey){
		System.out.println("updateBean validate Passkey");
		
		BeanFactory ctx=(new ClassPathXmlApplicationContext("SpringDAO.xml"));
		DasRegistrySql registry=(DasRegistrySql)ctx.getBean("registryBean");
		DasSource ds = registry.getDasSource(ds_id);
		boolean ok = registry.checkPasskey(ds.getUrl(), passkey);
		
		if ( ok)
			return PASSKEY_OK;
		else
			return PASSKEY_WRONG;
		
	}


}


